package com.nononsenseapps.feeder.pad.ui

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.core.view.GravityCompat
import com.nononsenseapps.feeder.ui.home.FeedsAdapter
import com.nononsenseapps.feeder.ui.reader.webview.ReaderWebViewFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import androidx.appcompat.widget.Toolbar
import androidx.drawerlayout.widget.DrawerLayout
import androidx.recyclerview.widget.RecyclerView
import com.nononsenseapps.feeder.pad.R
import com.nononsenseapps.feeder.db.room.ID_ALL_FEEDS
import com.nononsenseapps.feeder.db.room.ID_UNSET
import com.nononsenseapps.feeder.pad.ui.feed.FeedFragment
import com.nononsenseapps.feeder.ui.AbstractFeedActivity
import com.nononsenseapps.feeder.ui.base.EXTRA_FEEDITEMS_TO_MARK_AS_NOTIFIED
import com.nononsenseapps.feeder.ui.common.*
import com.nononsenseapps.feeder.util.*
import timber.log.Timber

class FeedActivity :  AbstractFeedActivity() {

    lateinit var feedFragment:FeedFragment
    lateinit var deviderPanel:BicontLayout

    private lateinit var toolbar : Toolbar
    private lateinit var drawer_layout : DrawerLayout
    private lateinit var navdrawer_list : RecyclerView
    private lateinit var fabButton : DragFloatActionButton

    var drawerOpened=false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_navigation)
        toolbar=findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)

        drawer_layout=findViewById(R.id.drawer_layout)
        navdrawer_list=findViewById(R.id.navdrawer_list)
        fabButton=findViewById(R.id.fab)

        fabButton.setOnClickListener {
            fabClickListener?.fabOnClickListener()
        }

        fabButton.setDoubleClickCallback {
            fabClickListener?.fabOnDoubleClickListener()
        }

        fabButton.setLongClickCallback{
            fabClickListener?.fabOnLongClickListener()
        }

        feedFragment= supportFragmentManager.findFragmentById(R.id.feed_fragment) as FeedFragment

        deviderPanel=findViewById(R.id.devider_panel)
        deviderPanel.apply {
            initLayout(R.id.devider_panel_left, R.id.devider_panel_devider, R.id.devider_panel_right) {

            }
            panelOpenHideChangedListener=object:PanelOpenHideChangedListener{
                override fun leftPanelMaxed() {
                    feedFragment.changeToMaxPanelModel(true)
                    navController.navigate(R.id.welcomeFragment)
                }

                override fun rightPanelMaxed() {
                    feedFragment.setHasOptionsMenu(false)
                }

                override fun resetToBefore() {
                    feedFragment.changeToMaxPanelModel(false)
                    feedFragment.setHasOptionsMenu(true)
                }
            }
        }


        val toggle = ActionBarDrawerToggle(
                this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
        drawer_layout.addDrawerListener(toggle)
        toggle.syncState()

        //drawer_layout.setScrimColor(Color.TRANSPARENT)

        drawer_layout.addDrawerListener(object:DrawerLayout.DrawerListener{
            override fun onDrawerStateChanged(newState: Int) {
            }

            override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
                val mContent=drawer_layout.getChildAt(0)
                val scale=1-slideOffset
                mContent.translationX=drawerView.measuredWidth*(1-scale)
                mContent.invalidate()
            }

            override fun onDrawerClosed(drawerView: View) {
                drawerOpened=false
                deviderPanel.setRightViewMargins(right = 0)
            }

            override fun onDrawerOpened(drawerView: View) {
                drawerOpened=true
                if(deviderPanel.isRightPanelMaxModel())
                    deviderPanel.resetToBefore()
                deviderPanel.setRightViewMargins(right = drawerView.width)
            }

        })

        (drawer_layout as PadDrawerLayout).interruptTouchEventDisableCheck={ x, y->
            //Timber.d("interruptTouchEventDisable: ${drawerOpened&&!feedFragment.maxPanelModel&&feedFragment.requireView().isUnder(x,y)}....")
            drawerOpened&&!feedFragment.maxPanelModel&&feedFragment.requireView().isUnder(x,y)
        }

        //val appBarConfiguration = AppBarConfiguration(navController.graph, drawer_layout)
        //toolbar.setupWithNavController(navController, appBarConfiguration)

        // Drawer stuff
        navdrawer_list.setHasFixedSize(true)
        navdrawer_list.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)


        navAdapter = FeedsAdapter(object : AbstractOnNavigationItemClickListener() {
            override fun onNavigationItemClick(id: Long, displayTitle: String?, url: String?, tag: String?) {
                if(feedFragment.maxPanelModel)
                   drawer_layout.closeDrawer(GravityCompat.START)
                feedFragment.navigateToFeedFragment(id,tag)
            }

            override fun deleteFeed(id: Long) {
                if(PrefUtils.getLastOpenFeedId(this@FeedActivity)==id) {
                    feedFragment.navigateToFeedFragment(ID_ALL_FEEDS, null)
                }
                super.deleteFeed(id)
            }

            override fun deleteFeedsInTag(tag: String) {
                super.deleteFeedsInTag(tag)
                feedFragment.navigateToFeedFragment(ID_ALL_FEEDS, null)
            }


        })
        navdrawer_list.adapter = navAdapter

        // Navigation stuff
        navController.addOnDestinationChangedListener { _, destination, _ ->
            Timber.d("call on Navigation change listener")

            /*fabOnClickListener = {}
            fabOnDoubleClickListener={}
            fabOnLongClickListener={}*/


            // Fab handling
            when (destination.id) {
                /*R.id.feedFragment -> {
                    //fab.setImageResource(R.drawable.ic_forward_top)
                    fab.show()
                }*/
                R.id.welcomeFragment->{
                    fabButton.show()
                    feedFragment.showFeedCommandFab()
                }
                R.id.readerFragment -> {
                    //fab.setImageResource(R.drawable.ic_forward_next)
                    fabButton.show()
                }
                else -> {
                    fabButton.hide()
                }
            }

            // Toolbar hiding
            when (destination.id) {
                //R.id.feedFragment -> hideableToolbar()
                R.id.welcomeFragment -> hideableToolbar()
                R.id.readerFragment -> hideableToolbar()
                R.id.codeViewFragment -> hideableToolbar()
                R.id.readerWebViewFragment -> hideableToolbar()
                else -> fixedToolbar()
            }
        }
        handleSettingIntent()
    }

    override fun onBackPressed() {
        if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
            drawer_layout.closeDrawer(GravityCompat.START)
        } else {
            var handled: Boolean = supportFragmentManager
                    .primaryNavigationFragment
                    ?.childFragmentManager
                    ?.primaryNavigationFragment.let {
                when (it) {
                    is ReaderWebViewFragment -> it.goBack()
                    is FeedFragment ->{
                        var ret=false
                        if ((System.currentTimeMillis() - mBackKeyDownTime) > 2000) {
                            Toast.makeText(this, "再按一次退出",Toast.LENGTH_SHORT).show()
                            doSomethingMemoryIntensive()
                            mBackKeyDownTime = System.currentTimeMillis()
                            ret=true
                        }
                        ret
                    }
                    else -> false
                }
            }

            if (!handled) {
                super.onBackPressed()
            }
        }
    }


    override fun onResume() {
        super.onResume()
        intent?.extras?.let { arguments ->
            val feedId = arguments.getLong(ARG_FEED_ID, ID_UNSET)
            val url = arguments.getString(ARG_LINK)
            val enclosure=arguments.getString(ARG_ENCLOSURE)
            val feedTag = arguments.getString(ARG_FEED_TAG)
            val itemId=arguments.getLong(ARG_ID, ID_UNSET)

            Timber.d("feed activity catch notification feedId:$feedId\turl:$url\tfeedTag:$feedTag\t itemId:$itemId\t..")

            arguments.getLongArray(EXTRA_FEEDITEMS_TO_MARK_AS_NOTIFIED)?.let {
                launch(Dispatchers.Default) {
                    feedItemDao.markAsNotified(it.toList())
                }
            }

            if(itemId!= ID_UNSET)
                feedFragment.notificationToReaderFragment(feedId,itemId)
            else if(url!=null||enclosure!=null)
                feedFragment.notificationToWebViewFragment(feedId,url,enclosure)
            else if(feedId!= ID_UNSET||!feedTag.isNullOrEmpty())
                feedFragment.navigateToFeedFragment(feedId,feedTag)

        }
        syncFeedsMaybe()
    }


    override fun openNavDrawer() {
        drawer_layout.openDrawer(GravityCompat.START)
    }

    override fun debug(): Boolean=true

    override fun getFab(): DragFloatActionButton =fabButton

    override fun navHostFragment(): Int =R.id.nav_host_fragment

    override fun getToolBar(): Toolbar =toolbar

    override fun handleSettingIntent() {
        if (intent?.action == Intent.ACTION_MANAGE_NETWORK_USAGE) {
            navController.navigate(R.id.settingsFragment)
        }
    }

    override fun navigateToFeedRuleFragment(feedId: Long?, regContent: String?, adFlag: Boolean?) {
        feedFragment.navigateToFeedRuleFragment(feedId,regContent,adFlag)
    }

}